<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.thinkphp.cn/ All rights reserved.
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
namespace app\attachment\controller;

use app\common\controller\Base;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 七牛云对象上传
 * @author nagi
 */
class QiniuUpload extends Base
{
    private $bucket;
    private $token;
    private $uploadMgr;
    private $bucketMgr ;

    public function __construct($driver)
    {
        // 构建鉴权对象
        $auth = new Auth($driver['accessKey'], $driver['secretKey']);
        // 初始化空间
        $this->bucket = $driver['bucket'];
        // 生成上传 Token
        $this->token = $auth->uploadToken($driver['bucket']);
        // 初始化 UploadManager 对象并进行文件的上传。
        $this->uploadMgr = new UploadManager();
        // 初始化 BucketManager 对象并进行文件的上传。
        $config = new \Qiniu\Config();
        $this->bucketMgr = new \Qiniu\Storage\BucketManager($auth, $config);
    }

    /**
     * 上传
     * @param null $info
     * @return array
     */
    public function upload($info = null)
    {
        if (empty($info)) {
            $info = $this->dealFiles($_FILES);
            $info = $info['file'];
        }

        // 要上传文件的本地路径
        $filepath = $info['tmp_name'];

        //文件名
        $object = $info['md5'] . '.' . $info['ext'];
//        $object = $info['name'];
        //存储目录
        $path = date('Y-m-d', time());
        $key = $path . '/' . $object;

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($res, $err) = $this->uploadMgr->putFile($this->token, $key, $filepath);
        if ($err === null) {
            $result = ['code' => 0, 'msg' => '上传成功', 'name' => $object, 'url' => $res['key']];
        } else {
            trace($err,'error');
            $result = ['code' => -1, 'msg' => '上传失败', 'data' => null];
        }
        return $result;
    }

    /**
     * 删除文件
     * @param string $object 对象名
     * @param string $driver 上传驱动
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($object = '', $driver = '')
    {
        if (empty($object)) {
            $object = $this->request->param('object');
        }
        $err = $this->bucketMgr->delete($this->bucket, $object);
        if ($err) {
            trace($err,'error');
            $result = ['code' => -1, 'msg' => '删除失败'];
        } else {
            deleteModel('attachment', ['path' => $object, 'driver' => $driver]);
            $result = ['code' => 0, 'msg' => '删除成功'];
        }
        return $result;
    }

    /**
     * 转换上传文件数组变量为正确的方式
     * @access private
     * @param array $files 上传的文件变量
     * @return array
     */
    private function dealFiles($files)
    {
        $fileArray = array();
        $n = 0;
        foreach ($files as $key => $file) {
            if (is_array($file['name'])) {
                $keys = array_keys($file);
                $count = count($file['name']);
                for ($i = 0; $i < $count; $i++) {
                    $fileArray[$n]['key'] = $key;
                    foreach ($keys as $_key) {
                        $fileArray[$n][$_key] = $file[$_key][$i];
                    }
                    $n++;
                }
            } else {
                $fileArray = $files;
                break;
            }
        }
        return $fileArray;
    }

}
